package com.quanyan.club.mq.consumer;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.mapper.ClubMemberMapper;
import com.quanyan.club.mapper.TbClubMedalRelationMapper;
import com.quanyan.club.mapper.TbClubMsgConsumerRecordMapper;
import com.quanyan.club.mapper.TbMedalRuleMapper;
import com.quanyan.club.mq.ClubMedalMsg;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.enums.SysClubMedalConditionEnum;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.user.mq.UserMedalMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by zhang on 16/8/2.
 */
@Component()
public class MqClubMedalConsumer extends AbstractMqConsumer {

    public static final Logger logger = LoggerFactory.getLogger(MqClubMedalConsumer.class);

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;
    @Autowired
    private TbClubMedalRelationMapper clubMedalRelationMapper;
    @Autowired
    private TbMedalRuleMapper medalRuleMapper;
    @Autowired
    private TbClubMsgConsumerRecordMapper clubMsgConsumerRecordMapper;
    @Autowired
    private ClubMemberMapper clubMemberMapper;

    @PostConstruct
    @Override
    public void start() {
        logger.info("俱乐部勋章消费mq启动成功: {}",nameServerAddress);
        super.start();
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {

        MessageExt messageExt = messages.get(0);
        String msgId = messageExt.getKeys();
        logger.info("收到俱乐部勋章mq消息，msgId：{}",msgId);
        TbClubMsgConsumerRecord clubMsgConsumerRecord = this.getClubMsgConsumerRecord(msgId,MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC,
                MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS,null);
        if (clubMsgConsumerRecord == null) {

            byte[] bodyBytes = messageExt.getBody();
            ClubMedalMsg clubMedalMsg = (ClubMedalMsg) ObjectUtil.toObject(bodyBytes);

            Integer clubId = clubMedalMsg.getClubId();
            Integer medalId = clubMedalMsg.getMedalId();
            Integer uid = clubMedalMsg.getUid();
            //完美无缺勋章
            if (medalId.equals(SysClubMedalConditionEnum.PERFECT.getId())) {
                List<Integer> clubIdList = clubMemberMapper.selectClubIdByUid(uid);
                int k = 0;
                for (Integer integer : clubIdList) {
                    int n = updateMedal(medalId,integer,msgId);
                    k = k + n;
                }
                if (k > 0 ){
                    return MqConsumerStatus.CONSUMER_SUCCESS;
                } else {
                    return MqConsumerStatus.RE_CONSUME_LATER;
                }

            }

            insertClubMsgConsumerRecord(uid, clubId, msgId, MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC, MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS, "");

            logger.info("开始消费用户勋章消息：【msgId】:【{}】;【clubId】:【{}】;【medalId】:【{}】",msgId,clubId,medalId);

            int n = updateMedal(medalId,clubId,msgId);
            if (n > 0) {
                return MqConsumerStatus.CONSUMER_SUCCESS;
            }


        }
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @Override
    protected String getConsumerGroup() {
        return MqConstants.ClubMedalProducer.CLUB_MEDAL_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return MqConstants.ClubMedalProducer.CLUB_MEDAL_INSTANCE;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC,
                MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS);
        return mqTopics;
    }

    /**
     * 获取俱乐部勋章信息
     * @param medalId
     * @param clubId
     * @return
     */
    private List<TbClubMedalRelation> getClubMedalRelation(Integer medalId,Integer clubId){
        TbClubMedalRelationExample example = new TbClubMedalRelationExample();
        example.createCriteria().andClubIdEqualTo(clubId).andMedalIdEqualTo(medalId);
        List<TbClubMedalRelation> clubMedalRelationList = this.clubMedalRelationMapper.selectByExample(example);
        return clubMedalRelationList;
    }

    /**
     * 更新用户勋章
     * @param medalId
     * @param clubId
     * @param clubMedalRelation
     * @return
     */
    private int updateClubMedalRelation(Integer medalId,Integer clubId,TbClubMedalRelation clubMedalRelation){

        TbClubMedalRelationExample example = new TbClubMedalRelationExample();
        example.createCriteria().andMedalIdEqualTo(medalId).andClubIdEqualTo(clubId);

        int n = this.clubMedalRelationMapper.updateByExampleSelective(clubMedalRelation,example);
        return n;
    }

    /**
     * 获取用户勋章规则
     * @param medalId
     * @return
     */
    private List<TbMedalRule> getMedalRuleList(Integer medalId){
        TbMedalRuleExample example = new TbMedalRuleExample();
        example.setOrderByClause("medal_start_level desc");
        example.createCriteria().andMedalIdEqualTo(medalId);
        List<TbMedalRule> medalRuleList = this.medalRuleMapper.selectByExample(example);
        return medalRuleList;
    }

    /**
     * 获取俱乐部消息消费记录
     * @param msgId
     * @param topic
     * @param tag
     * @return
     */
    private TbClubMsgConsumerRecord getClubMsgConsumerRecord(String msgId,String topic,String tag,Integer uid){
        TbClubMsgConsumerRecordExample example = new TbClubMsgConsumerRecordExample();
        TbClubMsgConsumerRecordExample.Criteria criteria = example.createCriteria();
        criteria.andMsgIdEqualTo(msgId);
        criteria.andTopicEqualTo(topic);
        criteria.andTagEqualTo(tag);
        if (uid != null) {
            criteria.andUidEqualTo(uid);
        }
        List<TbClubMsgConsumerRecord> clubMsgConsumerRecordList = clubMsgConsumerRecordMapper.selectByExample(example);
        if (clubMsgConsumerRecordList.isEmpty()) {
            return null;
        } else {
            return clubMsgConsumerRecordList.get(0);
        }
    }

    /**
     * 插入俱乐部消息消费记录
     * @param clubId
     * @return
     */
    private int insertClubMsgConsumerRecord(Integer uid,Integer clubId,String msgId,String topic,String tag,String remark){
        TbClubMsgConsumerRecord clubMsgConsumerRecord = new TbClubMsgConsumerRecord();
        clubMsgConsumerRecord.setUid(uid);
        clubMsgConsumerRecord.setClubId(clubId);
        clubMsgConsumerRecord.setMsgId(msgId);
        clubMsgConsumerRecord.setTopic(topic);
        clubMsgConsumerRecord.setTag(tag);
        clubMsgConsumerRecord.setRemark(remark);
        int n = clubMsgConsumerRecordMapper.insertSelective(clubMsgConsumerRecord);
        return n;
    }

    /**
     * 更新俱乐部消息消费状态
     * @param msgId
     * @param topic
     * @param tag
     * @param status
     * @return
     */
    private int updateClubMsgConsumerRecord(String msgId,String topic,String tag,Boolean status){
        TbClubMsgConsumerRecord clubMsgConsumerRecord = new TbClubMsgConsumerRecord();
        clubMsgConsumerRecord.setStatus(status);

        TbClubMsgConsumerRecordExample example = new TbClubMsgConsumerRecordExample();
        TbClubMsgConsumerRecordExample.Criteria criteria = example.createCriteria();
        criteria.andMsgIdEqualTo(msgId);
        criteria.andTopicEqualTo(topic);
        criteria.andTagEqualTo(tag);
        int n = clubMsgConsumerRecordMapper.updateByExampleSelective(clubMsgConsumerRecord,example);
        return n;
    }

    /**
     * 更新勋章
     * @param medalId
     * @param clubId
     * @param msgId
     * @return
     */
    private int updateMedal(Integer medalId,Integer clubId,String msgId){

        List<TbClubMedalRelation> clubMedalRelationList = this.getClubMedalRelation(medalId, clubId);
        if (!clubMedalRelationList.isEmpty()) {
            TbClubMedalRelation clubMedalRelation = clubMedalRelationList.get(0);

            Integer ownValue = clubMedalRelation.getOwnValue() + 1;
            clubMedalRelation.setOwnValue(ownValue);

            List<TbMedalRule> medalRuleList = this.getMedalRuleList(medalId);
            for (TbMedalRule tbMedalRule : medalRuleList) {

                if(tbMedalRule.getMedalStartLevel().intValue() ==3){
                    if (!clubMedalRelation.getGoalValue().equals(tbMedalRule.getStandardValue())) {
                        clubMedalRelation.setGoalValue(tbMedalRule.getStandardValue());
                    }
                }
                if(ownValue.intValue() >= tbMedalRule.getStandardValue().intValue()){
                    clubMedalRelation.setMedalStartLevel(tbMedalRule.getMedalStartLevel());
                    break;
                }
            }
            int n = this.updateClubMedalRelation(medalId,clubId,clubMedalRelation);
            if (n > 0) {
                updateClubMsgConsumerRecord(msgId,MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC,MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS,true);
                return n;
            }
        }else{
            logger.warn("该俱乐部【{}】 该勋章【{}】不存在",clubId,medalId);
            return 0;
        }
        return 0;
    }
}
